﻿using System;
using System.Collections.Generic;
using System.Text;

using ShootSearch.Core;
using ShootSearch.FileSystem;
using ShootSearch.Indexers;

using Quartz;
using ShootSearch.Logging;

namespace ShootSearch.Jobs
{
    public class IndexBuilderJob : InputOutputJob
    {
        protected IndexBuilderJobConfig config;
        protected IIndexer indexer;

        public IndexBuilderJob()
        {
            Config = new IndexBuilderJobConfig();
        }

        public override SpiderManConfig Config
        {
            get
            {
                return config;
            }
            set
            {
                if (value is IndexBuilderJobConfig)
                {
                    base.Config = value;
                    config = value as IndexBuilderJobConfig;
                }
            }
        }

        protected override bool InitializeProgress()
        {
            if (!base.InitializeProgress()) return false;
            indexer = config.Indexer.GetObjectWithConfig() as IIndexer;
            if (indexer == null) return false;
            indexer.Logger = this.Logger;
            return true;
        }
        
        protected override bool BeforeProcessFSID(InputOutputArgument arg)
        {
            bool baseOpen = base.BeforeProcessFSID(arg);
            bool indexCreate = indexer.Create(contextPath, arg);
            return baseOpen && indexCreate;
        }
        
        protected override void AfterProcessFSID(InputOutputArgument arg)
        {
            base.AfterProcessFSID(arg);
            indexer.Close();
            Log.Info(Logger, "Index completed!");
        }
        
        protected override void ProcessDocument(IFileObject doc)
        {
            Log.Info(Logger, "Add index: " + doc.Url);
            indexer.Add(doc);
        }
        
        public override void Dispose()
        {
            base.Dispose();
            if (indexer != null)
            {
                indexer.Dispose();
            }
            Log.Info(Logger, "IndexBuilder Disposed");
        }
    }
}
